package com.rkc.interceptor;

import com.rkc.enums.BizCodeEnum;
import com.rkc.model.LoginUser;
import com.rkc.utils.CommonUtil;
import com.rkc.utils.JsonData;
import com.rkc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author `RKC`
 * @date 2021/10/17 15:53
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("token");
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getParameter("token");
        }
        if (StringUtils.isBlank(accessToken)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }
        //token不为空，进行检测
        Claims claims = JwtUtil.checkJWT(accessToken);
        if (Objects.isNull(claims)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }
        long id = Long.parseLong(claims.get("id").toString());
        String headImg = claims.get("head_img", String.class);
        String name = claims.get("name", String.class);
        String mail = claims.get("mail", String.class);
        LoginUser loginUser = LoginUser.builder().id(id).headImg(headImg).name(name).mail(mail).build();
        //可以通过setAttribute将loginUser传递过去    request.setAttribute("loginUser", loginUser)
        THREAD_LOCAL.set(loginUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
